package com.ruoyi.sso.service.impl;


import com.ruoyi.sso.domain.SsoUser;
import com.ruoyi.sso.other.utils.CookieUtils;
import com.ruoyi.sso.service.AccessTokenManager;
import com.ruoyi.sso.service.TicketGrantingTicketManager;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.ruoyi.sso.other.constant.SsoConstant.TGC;


/**
 * 服务端凭证管理
 *
 * @author Joe
 */
@Component
public class SessionManager {

    @Autowired
    private AccessTokenManager accessTokenManager;
    @Autowired
    private TicketGrantingTicketManager ticketGrantingTicketManager;

    public String setUser(SsoUser user, HttpServletRequest request, HttpServletResponse response) {
        String tgt = getCookieTgt(request);
        // cookie中没有
        if (StringUtils.isEmpty(tgt)) {
            tgt = ticketGrantingTicketManager.generate(user);
            // TGT存cookie，和Cas登录保存cookie中名称一致为：TGC
            CookieUtils.addCookie(TGC, tgt, "/", request, response);
        } else if (ticketGrantingTicketManager.getAndRefresh(tgt) == null) {
            ticketGrantingTicketManager.create(tgt, user);
        } else {
            ticketGrantingTicketManager.set(tgt, user);
        }
        return tgt;
    }

    public SsoUser getUser(HttpServletRequest request) {
        String tgt = getCookieTgt(request);
        if (StringUtils.isEmpty(tgt)) {
            return null;
        }
        return ticketGrantingTicketManager.getAndRefresh(tgt);
    }

    public void invalidate(HttpServletRequest request, HttpServletResponse response) {
        String tgt = getCookieTgt(request);
        if (StringUtils.isEmpty(tgt)) {
            return;
        }
        // redis删除登录凭证
        ticketGrantingTicketManager.remove(tgt);
        // 统一登录页面删除凭证Cookie
        CookieUtils.removeCookie(TGC, "/", response);
        // 删除所有tgt对应的调用凭证，并通知客户端登出注销本地session
        accessTokenManager.remove(tgt);
    }

    public String getTgt(HttpServletRequest request) {
        String tgt = getCookieTgt(request);
        if (StringUtils.isEmpty(tgt) || ticketGrantingTicketManager.getAndRefresh(tgt) == null) {
            return null;
        } else {
            return tgt;
        }
    }

    private String getCookieTgt(HttpServletRequest request) {
        return CookieUtils.getCookie(request, TGC);
    }
}
